'use strict';

// 云对象名：credential-service
module.exports = {
  /**
   * 获取证书列表
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @param {string} type - 证书类型
   * @returns {object} 证书列表
   */
  async getCertificates(userId, token, type) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 存储所有证书数据
      let allCertificates = [];
      
      // 查询所有可能的认证表
      const credentialTables = [
        { collection: 'referee_credentials', role_type: 1 },
        { collection: 'supervisor_credentials', role_type: 3 },
        { collection: 'admin_credentials', role_type: 4 }
      ];
      
      // 遍历查询各个认证表
      for (const table of credentialTables) {
        try {
          const result = await db.collection(table.collection)
            .where({ user_id: currentUserId })
            .get();
          
          if (result.data && result.data.length > 0) {
            // 为每个记录添加角色类型信息
            const certificates = result.data.map(item => ({
              ...item,
              role_type: table.role_type,
              collection_source: table.collection
            }));
            allCertificates = allCertificates.concat(certificates);
          }
        } catch (error) {
          console.error(`查询${table.collection}失败:`, error);
        }
      }
      
      // 如果指定了类型，进行过滤
      if (type) {
        const typeMap = {
          'referee': 1,
          'supervisor': 3,
          'admin': 4
        };
        const roleType = typeMap[type];
        if (roleType) {
          allCertificates = allCertificates.filter(cert => cert.role_type === roleType);
        }
      }
      
      // 按时间倒序排列（优先使用register_date）
      allCertificates.sort((a, b) => {
        const dateA = new Date(a.register_date || a.update_date || a.create_date || a.create_time || 0);
        const dateB = new Date(b.register_date || b.update_date || b.create_date || b.create_time || 0);
        return dateB - dateA;
      });
      
      console.log(`用户${currentUserId}的证书数据:`, allCertificates);
      
      return {
        code: 0,
        message: '获取成功',
        data: allCertificates
      };
    } catch (error) {
      console.error('获取证书列表失败:', error);
      return {
        code: -1,
        message: '获取证书列表失败: ' + error.message
      };
    }
  },

  /**
   * 获取认证信息
   * @param {string|object} userIdOrParams - 用户ID或参数对象
   * @param {string} token - 用户token
   * @param {string} type - 认证类型
   * @returns {object} 认证信息
   */
  async getCredentialInfo(userIdOrParams, token, type) {
    try {
      const db = uniCloud.database();
      
      // 兼容对象参数和分别传参两种方式
      let userId, actualToken, actualType;
      
      if (typeof userIdOrParams === 'object' && userIdOrParams !== null) {
        // 对象参数方式
        userId = userIdOrParams.userId;
        actualToken = userIdOrParams.token;
        actualType = userIdOrParams.type;
      } else {
        // 分别传参方式
        userId = userIdOrParams;
        actualToken = token;
        actualType = type;
      }
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (actualToken) {
        try {
          const tokenResult = await db.collection('users').where({
            token: actualToken
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 如果没有指定类型，查询所有认证表，返回最新的一条
      if (!actualType) {
        const credentialTables = [
          { collection: 'referee_credentials', role_type: 1 },
          { collection: 'supervisor_credentials', role_type: 3 },
          { collection: 'admin_credentials', role_type: 4 }
        ];
        
        let latestCredential = null;
        let latestDate = 0;
        
        for (const table of credentialTables) {
          try {
            const result = await db.collection(table.collection)
              .where({ user_id: currentUserId })
              .get();
              
            if (result.data && result.data.length > 0) {
              for (const credential of result.data) {
                credential.role_type = table.role_type;
                const credentialDate = new Date(credential.register_date || credential.update_date || credential.create_date || 0);
                if (credentialDate > latestDate) {
                  latestDate = credentialDate;
                  latestCredential = credential;
                }
              }
            }
          } catch (error) {
            console.error(`查询${table.collection}失败:`, error);
          }
        }
        
        return {
          code: 0,
          message: '获取成功',
          data: latestCredential
        };
      }
      
      // 根据类型查询不同的认证表
      let collectionName = '';
      switch (actualType) {
        case 'referee':
          collectionName = 'referee_credentials';
          break;
        case 'supervisor':
          collectionName = 'supervisor_credentials';
          break;
        case 'admin':
          collectionName = 'admin_credentials';
          break;
        default:
          return {
            code: -1,
            message: '不支持的认证类型'
          };
      }
      
      // 查询认证信息
      const credentialResult = await db.collection(collectionName)
        .where({ user_id: currentUserId })
        .get();
      
      return {
        code: 0,
        message: '获取成功',
        data: credentialResult.data && credentialResult.data.length > 0 ? credentialResult.data[0] : null
      };
    } catch (error) {
      console.error('获取认证信息失败:', error);
      return {
        code: -1,
        message: '获取认证信息失败: ' + error.message
      };
    }
  },

  /**
   * 获取认证列表
   * @param {string} type - 认证类型
   * @param {string} status - 状态
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @returns {object} 认证列表
   */
  async getCredentialList(type, status, page = 1, limit = 10) {
    try {
      const db = uniCloud.database();
      
      // 根据类型确定集合名称
      let collectionName = '';
      switch (type) {
        case 'referee':
          collectionName = 'referee_credentials';
          break;
        case 'supervisor':
          collectionName = 'supervisor_credentials';
          break;
        case 'admin':
          collectionName = 'admin_credentials';
          break;
        default:
          return {
            code: -1,
            message: '不支持的认证类型'
          };
      }
      
      // 构建查询条件
      const where = {};
      if (status) {
        where.status = status;
      }
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询认证列表
      const credentialsResult = await db.collection(collectionName)
        .where(where)
        .orderBy('create_date', 'desc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection(collectionName)
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: credentialsResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取认证列表失败:', error);
      return {
        code: -1,
        message: '获取认证列表失败: ' + error.message
      };
    }
  },

  /**
   * 提交认证申请
   * @param {string} type - 认证类型
   * @param {object} credentialData - 认证数据
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @returns {object} 提交结果
   */
  async submitCredential(type, credentialData, userId, token) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 根据类型确定集合名称
      let collectionName = '';
      switch (type) {
        case 'referee':
          collectionName = 'referee_credentials';
          break;
        case 'supervisor':
          collectionName = 'supervisor_credentials';
          break;
        case 'admin':
          collectionName = 'admin_credentials';
          break;
        default:
          return {
            code: -1,
            message: '不支持的认证类型'
          };
      }
      
      // 检查是否已有认证申请
      const existingCredential = await db.collection(collectionName)
        .where({ user_id: currentUserId })
        .get();
      
      if (existingCredential.data && existingCredential.data.length > 0) {
        return {
          code: -1,
          message: '您已提交过认证申请，请勿重复提交'
        };
      }
      
      // 准备认证数据
      const submitData = {
        ...credentialData,
        user_id: currentUserId,
        type: type,
        status: 'pending',
        create_date: new Date(),
        update_date: new Date()
      };
      
      // 提交认证申请
      const result = await db.collection(collectionName).add(submitData);
      const credentialId = result.id;

      return {
        code: 0,
        message: '认证申请提交成功',
        data: {
          id: credentialId
        }
      };
    } catch (error) {
      console.error('提交认证申请失败:', error);
      return {
        code: -1,
        message: '提交认证申请失败: ' + error.message
      };
    }
  },

  /**
   * 审核认证申请
   * @param {string} credentialId - 认证ID
   * @param {string} type - 认证类型
   * @param {string} status - 审核状态
   * @param {string} remark - 审核备注
   * @param {string} reviewerId - 审核者ID
   * @returns {object} 审核结果
   */
  async reviewCredential(credentialId, type, status, remark, reviewerId) {
    try {
      const db = uniCloud.database();
      
      if (!credentialId || !type || !status) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      // 根据类型确定集合名称
      let collectionName = '';
      switch (type) {
        case 'referee':
          collectionName = 'referee_credentials';
          break;
        case 'supervisor':
          collectionName = 'supervisor_credentials';
          break;
        case 'admin':
          collectionName = 'admin_credentials';
          break;
        default:
          return {
            code: -1,
            message: '不支持的认证类型'
          };
      }
      
      // 更新认证状态
      const updateData = {
        status: status,
        review_date: new Date(),
        update_date: new Date()
      };
      
      if (remark) {
        updateData.review_remark = remark;
      }
      
      if (reviewerId) {
        updateData.reviewer_id = reviewerId;
      }
      
      await db.collection(collectionName).doc(credentialId).update(updateData);
      
      // 如果审核通过，更新用户角色
      if (status === 'approved') {
        const credentialResult = await db.collection(collectionName).doc(credentialId).get();
        if (credentialResult.data && credentialResult.data.length > 0) {
          const credential = credentialResult.data[0];
          
          // 更新用户角色
          let userRole = 0;
          let roleText = '';
          switch (type) {
            case 'referee':
              userRole = 1;
              roleText = '裁判员';
              break;
            case 'supervisor':
              userRole = 3;
              roleText = '监督员';
              break;
            case 'admin':
              userRole = 4;
              roleText = '管理员';
              break;
          }
          
          await db.collection('users').doc(credential.user_id).update({
            role: userRole,
            credential_status: 'approved',
            update_time: new Date()
          });
          
          // 发送认证通过通知
          try {
            const notificationService = uniCloud.importObject('notification-service');
            
            await notificationService.sendNotification({
              userId: credential.user_id,
              type: 'credential_update',
              title: '身份认证审核通过',
              content: `恭喜！您的${roleText}身份认证已通过审核，现在您可以享受更多功能权限。`,
              relatedId: credentialId,
              senderId: reviewerId || 'system',
              extraData: {
                jump_type: 'credential_detail',
                jump_url: `/packageMy/my/credential-detail?type=${type}&id=${credentialId}`,
                credential_type: type,
                credential_id: credentialId,
                status: 'approved'
              }
            });
            
            console.log(`认证通过通知已发送给用户 ${credential.user_id}`);
          } catch (notifyError) {
            console.error('发送认证通过通知失败:', notifyError);
            // 不影响认证审核的主流程
          }
        }
      } else if (status === 'rejected') {
        // 认证被拒绝，发送拒绝通知
        try {
          const credentialResult = await db.collection(collectionName).doc(credentialId).get();
          if (credentialResult.data && credentialResult.data.length > 0) {
            const credential = credentialResult.data[0];
            
            let roleText = '';
            switch (type) {
              case 'referee':
                roleText = '裁判员';
                break;
              case 'supervisor':
                roleText = '监督员';
                break;
              case 'admin':
                roleText = '管理员';
                break;
            }
            
            const notificationService = uniCloud.importObject('notification-service');
            
            await notificationService.sendNotification({
              userId: credential.user_id,
              type: 'credential_update',
              title: '身份认证审核未通过',
              content: `很遗憾，您的${roleText}身份认证未通过审核。${remark ? '原因：' + remark : '请检查您提交的材料后重新申请。'}`,
              relatedId: credentialId,
              senderId: reviewerId || 'system',
              extraData: {
                jump_type: 'credential_detail',
                jump_url: `/packageMy/my/credential-detail?type=${type}&id=${credentialId}`,
                credential_type: type,
                credential_id: credentialId,
                status: 'rejected',
                reject_reason: remark
              }
            });
            
            console.log(`认证拒绝通知已发送给用户 ${credential.user_id}`);
          }
        } catch (notifyError) {
          console.error('发送认证拒绝通知失败:', notifyError);
          // 不影响认证审核的主流程
        }
      }
      
      return {
        code: 0,
        message: '审核完成'
      };
    } catch (error) {
      console.error('审核认证申请失败:', error);
      return {
        code: -1,
        message: '审核失败: ' + error.message
      };
    }
  },

  /**
   * 审核证书
   * @param {string} certificateId - 证书ID
   * @param {string} status - 审核状态
   * @param {string} remark - 审核备注
   * @param {string} reviewerId - 审核者ID
   * @returns {object} 审核结果
   */
  async reviewCertificate(certificateId, status, remark, reviewerId) {
    try {
      const db = uniCloud.database();
      
      if (!certificateId || !status) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      // 更新证书状态
      const updateData = {
        status: status,
        review_date: new Date(),
        update_date: new Date()
      };
      
      if (remark) {
        updateData.review_remark = remark;
      }
      
      if (reviewerId) {
        updateData.reviewer_id = reviewerId;
      }
      
      await db.collection('certificates').doc(certificateId).update(updateData);
      
      // 发送证书审核结果通知
      try {
        const certificateResult = await db.collection('certificates').doc(certificateId).get();
        if (certificateResult.data && certificateResult.data.length > 0) {
          const certificate = certificateResult.data[0];
          const notificationService = uniCloud.importObject('notification-service');
          
          if (status === 'approved') {
            // 证书审核通过
            await notificationService.sendNotification({
              userId: certificate.user_id,
              type: 'credential_update',
              title: '证书审核通过',
              content: `恭喜！您的证书已通过审核，现在可以正常使用。`,
              relatedId: certificateId,
              senderId: reviewerId || 'system',
              extraData: {
                jump_type: 'certificate_detail',
                jump_url: `/packageMy/my/certificate-detail?id=${certificateId}`,
                certificate_id: certificateId,
                status: 'approved'
              }
            });
            
            console.log(`证书审核通过通知已发送给用户 ${certificate.user_id}`);
          } else if (status === 'rejected') {
            // 证书审核拒绝
            await notificationService.sendNotification({
              userId: certificate.user_id,
              type: 'credential_update',
              title: '证书审核未通过',
              content: `很遗憾，您的证书未通过审核。${remark ? '原因：' + remark : '请检查您提交的材料后重新申请。'}`,
              relatedId: certificateId,
              senderId: reviewerId || 'system',
              extraData: {
                jump_type: 'certificate_detail',
                jump_url: `/packageMy/my/certificate-detail?id=${certificateId}`,
                certificate_id: certificateId,
                status: 'rejected',
                reject_reason: remark
              }
            });
            
            console.log(`证书审核拒绝通知已发送给用户 ${certificate.user_id}`);
          }
        }
      } catch (notifyError) {
        console.error('发送证书审核通知失败:', notifyError);
        // 不影响证书审核的主流程
      }
      
      return {
        code: 0,
        message: '证书审核完成'
      };
    } catch (error) {
      console.error('审核证书失败:', error);
      return {
        code: -1,
        message: '审核失败: ' + error.message
      };
    }
  },

  /**
   * 更新证书状态
   * @param {string} certificateId - 证书ID
   * @param {string} status - 状态
   * @param {string} operatorId - 操作者ID
   * @returns {object} 更新结果
   */
  async updateCertificateStatus(certificateId, status, operatorId) {
    try {
      const db = uniCloud.database();
      
      if (!certificateId || !status) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      // 更新证书状态
      const updateData = {
        status: status,
        update_date: new Date()
      };
      
      if (operatorId) {
        updateData.operator_id = operatorId;
      }
      
      await db.collection('certificates').doc(certificateId).update(updateData);
      
      return {
        code: 0,
        message: '状态更新成功'
      };
    } catch (error) {
      console.error('更新证书状态失败:', error);
      return {
        code: -1,
        message: '更新状态失败: ' + error.message
      };
    }
  },

  /**
   * 上传证书认证申请
   * @param {object} params - 参数对象
   * @param {string} params.token - 用户token
   * @param {object} params.credential - 证书信息
   * @param {string} params.certificateType - 证书类型
   * @returns {object} 上传结果
   */
  async uploadCertificate({ token, credential, certificateType }) {
    try {
      const db = uniCloud.database();
      
      // 从token获取用户ID
      const userInfo = await db.collection('users')
        .where({ token: token })
        .get();
        
      if (!userInfo.data || userInfo.data.length === 0) {
        return {
          code: -1,
          message: '用户未登录或登录已过期'
        };
      }
      
      const userId = userInfo.data[0]._id;
      
      // 确定使用哪个集合
      let collectionName;
      switch(certificateType) {
        case 'referee':
          collectionName = 'referee_credentials';
          break;
        case 'supervisor':
          collectionName = 'supervisor_credentials';
          break;
        case 'admin':
          collectionName = 'admin_credentials';
          break;
        default:
          return {
            code: -1,
            message: '无效的证书类型'
          };
      }
      
      // 处理图片URL，确保保留原始扩展名
      if (credential && credential.certificate_image) {
        const originalUrl = credential.certificate_image;
        
        // 处理临时文件路径
        if (originalUrl.startsWith('http://tmp/')) {
          const filename = originalUrl.split('/').pop();
          let extension = '.jpg'; // 默认扩展名
          
          // 尝试从文件名中提取原始扩展名
          if (filename.includes('.')) {
            const parts = filename.split('.');
            if (parts.length > 1) {
              extension = '.' + parts[parts.length - 1].toLowerCase();
            }
          }
          
          // 生成不带扩展名的基本文件名
          let baseFilename = filename;
          if (baseFilename.includes('.')) {
            baseFilename = baseFilename.substring(0, baseFilename.lastIndexOf('.'));
          }
          
          // 使用原始扩展名构建新的URL
          credential.certificate_image = `https://mp-5c0eb4c9-2068-4b5c-ac94-9481b66585a3.cdn.bspapp.com/cloudstorage/${baseFilename}${extension}`;
        }
      }
      
      // 检查是否已存在证书
      const existingCert = await db.collection(collectionName)
        .where({ user_id: userId })
        .get();
      
      let result;
      
      // 合并证书数据，添加状态和时间戳
      const certData = {
        ...credential,
        user_id: userId,
        status: 'pending', // 初始状态统一为pending
        create_time: new Date().getTime(), // 统一使用create_time字段
        update_time: new Date().getTime()
      };
      
      if (existingCert.data.length > 0) {
        // 更新现有证书
        result = await db.collection(collectionName)
          .doc(existingCert.data[0]._id)
          .update(certData);
        
        // 同步更新用户表的证书状态
        await db.collection('users')
          .doc(userId)
          .update({
            credential_status: 'pending',
            pending_role_type: parseInt(credential.role_type) // 添加待审核角色类型
          });
        
        return {
          code: 0,
          message: '证书信息更新成功，请等待审核',
          data: {
            id: existingCert.data[0]._id,
            updated: result.updated
          }
        };
      } else {
        // 创建新证书
        result = await db.collection(collectionName).add(certData);
        
        // 同步更新用户表的证书状态
        await db.collection('users')
          .doc(userId)
          .update({
            credential_status: 'pending',
            pending_role_type: parseInt(credential.role_type) // 添加待审核角色类型
          });
        
        return {
          code: 0,
          message: '证书提交成功，请等待审核',
          data: {
            id: result.id
          }
        };
      }
    } catch (error) {
      console.error('上传证书失败：', error);
      return {
        code: -1,
        message: '上传证书失败：' + error.message
      };
    }
  }
}; 